package com.demo.annotation.exception;

import com.demo.annotation.utils.BizException;
import com.demo.annotation.utils.ExceptionEnum;
import com.demo.annotation.utils.ResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //捕获格式校验失败的异常
    @ExceptionHandler({ConstraintViolationException.class, BindException.class})
    public ResultResponse constraintViolateExceptionHandler(Exception ex, HttpServletRequest request) {
        logger.error("数据格式校验失败！原因是：{}", ex.getMessage());
        StringBuilder stringBuilder = new StringBuilder();
        if (ex instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) ex;
            ConstraintViolation<?> next = constraintViolationException.getConstraintViolations().iterator().next();
            stringBuilder.append(next.getMessage());
        } else if (ex instanceof BindException) {
            BindException bindException = (BindException) ex;
            stringBuilder.append(Objects.requireNonNull(bindException.getBindingResult().getFieldError()).getDefaultMessage());
        }
        return ResultResponse.error(stringBuilder.toString());
    }

    /**
     * 处理业务逻辑异常
     */
    @ExceptionHandler(value = BizException.class)
    public ResultResponse bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return ResultResponse.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResultResponse nullPointExceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
        return ResultResponse.error(ExceptionEnum.BODY_NOT_MATCH);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResultResponse exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知异常！原因是:",e);
        return ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
    }
}
